
import axios from 'axios';
import config from '../mp.config.js';
import api from './sysapi';


//保存导入的项目路径信息
export async function saveProjectPathInfo(file,info){
    let projectInfo=await readProjectPathInfo(file);
    if(projectInfo==""){
        return false;
    }
    //入口项目路径
    projectInfo.entryProjectPath=info;
    //判断项目是否已经存在,不存在则添加,存在则修改入口项目路径
    if(projectInfo.list.indexOf(info)==-1){
        projectInfo.list.push(info)
    }
    let projectPathInfo = JSON.stringify(projectInfo,null,'\t');
    api.writeFileSync(file,projectPathInfo);
    return true;
}

//读取导入的项目路径信息
export async function readProjectPathInfo(path){
    let readFileJson=await api.readFileSync(path);
    if(readFileJson){
        return JSON.parse(readFileJson);
    }
    return "";
}




export function request(opts) {
    const { url, method='get', data, headers,noRefetch } = opts;
    
	return new Promise(async (resolve, reject) => {

        let token = localStorage.getItem('token');
        if(!token) {
            token=await getToken()
        }

        axios({url,method,data,headers:{...headers,token}}).then(async (res) => {

            if(res.data.code === 1001 || res.data.code === 1003) {
                //请求失败，没有传noRefetch，则重新请求。传了noRefetch，则不重新请求
                if(!noRefetch) {
                    // 删除过期的token
                    // localStorage.removeItem('token');
                    // token过期，重新获取token
                    token=await refreshToken(token);
                    resolve(request({url,method,data,headers:{...headers,token},noRefetch:true}));
                }
            }else{
                //请求失败，没有传noRefetch，则重新请求。传了noRefetch，则不重新请求
                if(!noRefetch) {
                    // 重新请求
                    resolve(request({url,method,data,headers:{...headers,token},noRefetch:true}));
                }else{
                    resolve(res.data);
                }
            }

        }).catch(err => {
            reject(err)
        })
	});

}

function getToken() {
	return new Promise((resolve, reject) => {
        axios({url:config.route.getToken}).then(res => {
            localStorage.setItem('token', res.data.data.token);
            resolve(res.data.data.token)
        }).catch(err => {
            reject(err)
        })
	});
}
//刷新token
export function refreshToken(token) {
	return new Promise((resolve, reject) => {
        axios({url:config.route.refreshToken,method:'post',data:{token}}).then(res => {
            if(res.data.code == 0) {
                localStorage.setItem('token', res.data.data.token);
            }
            resolve(res.data.data.token)
        }).catch(err => {
            reject(err)
        })
	});
}


/**
 * json对象转url参数
 * @param data 对象
 */
export function parseParams(data) {
	var result = [];
	for (var key in data) {
		var value = data[key];
		if (value != null && value != "") {
			if (value.constructor == Array) {
				value.forEach(function (_value) {
					result.push(key + "=" + _value);
				});
			} else {
				result.push(key + '=' + value);
			}
		} else {
			result.push(key + '=' + value);
		}
	}
	return '?' + result.join('&');
}
